﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AppHelper
{
    /// <summary>
    /// 应用程序启动窗口
    /// 用法：
    ///  private void Form1_Load(object sender, EventArgs e)
    ///  {
    ///      //启动加载等待
    ///      //StartingWindow startingWindow = new StartingWindow("应用程序名称","公司名称");
    ///      StartingWindow startingWindow = new StartingWindow("AppDemo", "dhsososo@163.com");
    ///      startingWindow.loadingHandler += () =>
    ///      {
    ///          //做要加载的动作
    ///          startingWindow.SetTips("等待中1");
    ///          Thread.Sleep(2000);
    ///          startingWindow.SetTips("等待中2");
    ///          Thread.Sleep(2000);
    ///          startingWindow.SetTips("等待中3");
    ///          Thread.Sleep(2000);
    ///      };
    ///      startingWindow.exitHandler += () =>
    ///      {
    ///          //点击退出时 做要退出加载的动作
    ///          startingWindow.SetTips("退出加载1");
    ///          Thread.Sleep(2000);
    ///          startingWindow.SetTips("退出加载2");
    ///          Thread.Sleep(2000);
    ///          startingWindow.SetTips("退出加载3");
    ///          Thread.Sleep(2000);
    ///      
    ///      };
    ///      
    ///      //
    ///      startingWindow.ShowDialog();
    ///  }
    /// </summary>
    public partial class StartingWindow : Form
    {
        [DllImport("user32.dll")]//拖动无窗体的控件
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;

        public delegate void CloseDelegate();//声明委托
        public delegate void SetTipsDelegate(String tips);//声明委托
        public delegate void LoadingHandler();//声明委托
        public delegate void ExitHandler();//声明委托

        public event LoadingHandler loadingHandler;
        public event ExitHandler exitHandler;

        //线程
        public Thread thread;

        public String Tips { get => ulab_Tips.Text; set => ulab_Tips.Text = value; }

        private DateTime startTime;

        private String useTimeStr;
        public StartingWindow()
        {
            InitializeComponent();
        }
        public StartingWindow(String title = "程序启动中",String companyName = "")
        {
            InitializeComponent();
            ulab_Title.Text = title;
            startTime = DateTime.Now;
            ulab_CompanyName.Text = companyName;
            LogHelper.Info("程序加载开始");
        }


        private void StartingWindow_MouseDown(object sender, MouseEventArgs e)
        { 
            //拖动窗体
            ReleaseCapture();
            SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
        }

        private void StartingWindow_Load(object sender, EventArgs e)
        {
            //遍历窗体所有控件，
            foreach (Control control in this.Controls)
            {
                //遍历后的操作...
                if(!(control is UISymbolLabel))
                    control.MouseDown += StartingWindow_MouseDown;
            }

            //启动线程
            thread = new Thread(() =>
            {
                if (loadingHandler != null)
                    loadingHandler();
                ThisClose();
                LogHelper.Info($"程序加载完成。用时：{useTimeStr}");
            });
            thread.Start();
        }

        /// <summary>
        /// 设置提示文字
        /// </summary>
        /// <param name="tips"></param>
        public void SetTips(String tips)
        {
            if (this.InvokeRequired)
            {
                SetTipsDelegate @delegate = new SetTipsDelegate(SetTips);
                this.Invoke(@delegate, tips);
            }
            else
            {
                Tips = tips;
            }
        }

        /// <summary>
        /// 关闭窗口  可用于其他线程
        /// </summary>
        public void ThisClose()
        {
            if (this.InvokeRequired)
            {
                CloseDelegate @delegate = new CloseDelegate(Close);
                this.Invoke(@delegate);
            }
            else
            {
                Close();
            }
        }

        private void uslab_Exit_Click(object sender, EventArgs e)
        {
            uslab_Exit.Enabled = false;
            LogHelper.Info("程序加载终止，用户退出");
            try
            {
                if(thread != null)
                    thread.Abort();
            }
            catch (Exception ex)
            {
                LogHelper.Info("程序加载终止，终止线程",ex);
            }
            thread = new Thread(() =>
            {
                LogHelper.Info("程序加载终止，启动退出处理");
                if (exitHandler != null)
                    exitHandler();
                LogHelper.Info("程序加载终止，退出处理完成");
                ThisClose(); 
                Application.Exit();
            });
            thread.Start(); 
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            TimeSpan ts = DateTime.Now - startTime;
            //获取开始时间
            DateTime start = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            //注意13位是整数加上4个零 
            DateTime ttt = start.Add(ts);
            useTimeStr  = ttt.ToString("mm:ss:fff");//精确到毫秒
            ulab_UseTime.Text = useTimeStr;
        }
    }
}
